package com.house.framework.extend;

import com.alibaba.fastjson.JSONObject;
import com.house.context.RequestContextKit;
import com.house.context.SpringContextKit;
import com.house.enhance.SessionExtend;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Log4j2
@Component
public class SessionExtendImpl implements SessionExtend {
    @Value("${session.allow}")
    public boolean sessionAllow;

    @Override
    public JSONObject getLoginUserSession() {
        JSONObject loginUser;
        HttpSession session = RequestContextKit.getRequest().getSession(false);
        Object user = session == null ? null :(sessionAllow ? session.getAttribute("loginUser") : null);
        if (null != user) {
            loginUser = (JSONObject) user;
        } else {
            String sessionId = getSessionId();
            if (StringUtils.isNotEmpty(sessionId)) {
                IUserSessionService sysUserService = SpringContextKit.getBean(IUserSessionService.class);
                loginUser = sysUserService.userLoginSession(sessionId);
            } else {
                loginUser = null;
            }
        }
        return loginUser;
    }

    @Override
    public void setLoginUserInfo(Map<String, Object> user) {
        if (!(user instanceof JSONObject))
            user = new JSONObject(user);
        RequestContextKit.getRequest().getSession(true).setAttribute("loginUser", user);
    }

    @Override
    public void removeSession(String key, SessionStatus sessionStatus) {
        HttpSession session = RequestContextKit.getRequest().getSession();
        if (null != session) {
            session.removeAttribute(key);
            sessionStatus.setComplete();
        }
        IUserSessionService sysUserService = SpringContextKit.getBean(IUserSessionService.class);
        sysUserService.deleteUserLoginSession(getSessionId());
    }

    @Override
    public String getSessionId() {
        return RequestContextKit.getSessionId();
    }
}
